﻿using Core.Framework.Model.Common;
using Core.Framework.Model.WebSockets;
using Core.Framework.Redis;
using Core.Framework.Redis.Queue_Helper;
using Core.Framework.Util.Common;
using Core.Service.TaskHandle;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.WebSockets;
using System.Text;

namespace Core.Middleware.WebSockets.TimerJobs
{
    /// <summary>
    /// 初始化客户端信息
    /// </summary>
    public class InitServiceClinetParameter : ITimerJob
    {

        IRedisHelper iRedis;

        public InitServiceClinetParameter()
        {
            iRedis = BuildServiceProvider.GetService<IRedisHelper>();
        }

        public void Execute(IJobExecutionContext context)
        {

            this.ClearTimerOutClientLink();

            this.UpdateRedisTempSubscriptions();

        }

        /// <summary>
        /// 清除心跳超时或者已经关闭的连接
        /// </summary>
        private void ClearTimerOutClientLink()
        {

            // 心跳已超过15S或者已经关闭的连接
            var timerOutClient = WebSocketApplication.ClientsPool.Where(a =>
                a.Value.EndHeartTime.AddSeconds(15) < DateTime.Now
                ||
                WebSocketApplication.closeStates.Contains(a.Key.State)
            );

            // 删除客户机器
            foreach (var item in timerOutClient)
            {
                WebSocketApplication.ClientLoginOut(item.Key);
            }
        }


        /// <summary>
        /// 更新Redis各主题模板订阅关键字集合
        /// </summary>
        private void UpdateRedisTempSubscriptions() 
        {
            List<Listener_Template> temps = new List<Listener_Template>();

            foreach (var item in WebSocketApplication.TempSubscriptions)
            {
                temps.Add(new Listener_Template
                {
                    template = item.Key,
                    Subscription = item.Value
                });
            }

            iRedis.HashSet(
                RedisQueueHelperParameter.QueueService,
                RedisQueueHelperParameter.ServiceClinet, new QueueService
                {
                    Title = CoreStartupHelper.GetConfigValue("Service:Title"),
                    ApiUrl = CoreStartupHelper.GetConfigValue("Service:Url"),
                    Temps = temps,
                    System = CoreStartupHelper.GetConfigValue("Service:System"),
                    EndRefreshTime = DateTime.Now
                });
        }

    }
}
